import React from 'react'
import { Button, Form, Input, message } from 'antd'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import './login.css'
import axios from 'axios';

export default function Login(props) {

  // 表单组件Form提交后触发的事件回调
  const onFinish = (values) => {  // values接收的是Form组件下所有表单项的内容
    // console.log(values);
    // 调用接口将收集到的表单数据作为参数发送到后端进行校验
    axios.get(`http://localhost:5000/users?username=${values.username}&password=${values.password}&roleState=true&_expand=role`).then((res) => {
      // console.log(res.data)    // 接收请求返回的数据
      if(res.data.length===0){  // 请求返回的数据长度为0，证明登录失败
        message.error("用户名或密码错误")
      }else{
        localStorage.setItem("token",JSON.stringify(res.data[0]))
        props.history.push('/home')
      }
    })
  }

  return (
    <div className='login'>
      <div className='FormContainer'>
        <div className='loginHeadline'>全球新闻发布系统</div>
        {/* 
            onFinish 是当当前表单提交后会触发的事件
        */}
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: 'Please input your Username!' }]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: 'Please input your Password!' }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
